<?php
/**
 * Login user
 * @author Joakim Jarsäter
 * 
 * @param $usr string - Username
 * @param $pwd string - Password
 * 
 * @return array
 */
function loginUser($usr, $pwd)
{
	$username = mysql_real_escape_string($usr);
	$password = md5($pwd);
	
	$sqlQuery = "SELECT persons.*, roles.name as role_name
				FROM persons
				JOIN roles ON roles.role = persons.role
				WHERE persons.role > 0
				AND persons.username = '$username'
				AND persons.password = '$password'
				LIMIT 1";
	
	$result = mysql_query($sqlQuery) or die (mysql_error());
	if($row = mysql_fetch_array($result))
	{
		return array("data" => $row, "valid" => "true");

	}
	return array("valid" => "false", "message" => "Wrong username or password!");
}

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? '"' . $theValue . '"' : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? '"' . doubleval($theValue) . '"' : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? '"' . $theValue . '"' : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

function GetSQLValueStringForSelect($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? '"%' . $theValue . '%"' : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? '"' . doubleval($theValue) . '"' : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? '"' . $theValue . '"' : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
?>